package com.qixin.modules.eaLoan.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.qixin.modules.ea.entity.EaCommunications;
import com.qixin.modules.eaApplication.entity.EaEntertainApply;
import com.qixin.modules.eaLoan.vo.EaLoanBillPrintVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.ConvertUpMoneyUtil;
import org.jeecg.common.util.DateFormatUtil;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.oConvertUtils;
import com.qixin.modules.eaLoan.entity.EaLoanbill;
import com.qixin.modules.eaLoan.service.IEaLoanbillService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.activity.service.ActivityCommonService;
import org.jeecg.modules.nc.entity.NcPersonnel;
import org.jeecg.modules.nc.service.INcInoutbusiclassService;
import org.jeecg.modules.nc.service.INcPersonnelService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: ea_loanbill
 * @Author: qixin-boot
 * @Date: 2022-01-21
 * @Version: V1.0
 */
@Api(tags = "借款单")
@RestController
@RequestMapping("/eaLoan/eaLoanbill")
@Slf4j
public class EaLoanbillController extends JeecgController<EaLoanbill, IEaLoanbillService> {
    @Autowired
    private IEaLoanbillService eaLoanbillService;
    @Autowired
    private INcPersonnelService ncPersonnelService;
    // 工作流公共执行类
    @Autowired
    private ActivityCommonService activityCommonService;
    @Autowired
    private INcInoutbusiclassService ncInoutbusiclassService;

    /**
     * 分页列表查询
     *
     * @param eaLoanbill
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "借款单-分页列表查询", notes = "借款单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(EaLoanbill eaLoanbill,
                                   @RequestParam(name = "billDateBegin", required = false) String billDateBegin,
                                   @RequestParam(name = "billDateEnd", required = false) String billDateEnd,
                                   @RequestParam(name="isUse", required = false) String isUse,
                                   @RequestParam(name="org", required = false) String org,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(name = "billCode", required = false) String billCode,
                                   HttpServletRequest req) {
        QueryWrapper<EaLoanbill> queryWrapper = QueryGenerator.initQueryWrapper(eaLoanbill, req.getParameterMap());
        //add-begin-by wujinbiao for 添加查询条件 列表排序，创建人
        if (StringUtils.isNotBlank(billDateBegin)) {
            queryWrapper.ge("bill_date", billDateBegin);
        }
        if (StringUtils.isNotBlank(billDateEnd)) {
            queryWrapper.le("bill_date", billDateEnd);
        }
        if(StringUtils.isNotBlank(isUse) && "1".equals(isUse)){
            queryWrapper.eq("company_code_id",org).and(
                    wrapper -> wrapper.isNull("ea_repaymentbill_id").or().eq("ea_repaymentbill_id","")
            );
        }
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.eq("create_by", loginUser.getId());
        if(StringUtils.isNotBlank(billCode)){
            // 单据编号模糊查询
            queryWrapper.like("bill_no",billCode);
        }
        queryWrapper.orderByDesc("create_time");

        //add-end-by wujinbiao for 添加查询条件
        Page<EaLoanbill> page = new Page<EaLoanbill>(pageNo, pageSize);
        IPage<EaLoanbill> pageList = eaLoanbillService.page(page, queryWrapper);
        List<EaLoanbill> records = pageList.getRecords();
        for (EaLoanbill eaLoanbill1 : records) {
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaLoanbill1.getPersonId());
            if (ncPersonnel != null) {
                eaLoanbill1.setPersonIdName(ncPersonnel.getName());
            }
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param eaLoanbill
     * @return
     */
    @AutoLog(value = "借款单-添加")
    @ApiOperation(value = "借款单-添加", notes = "借款单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody EaLoanbill eaLoanbill) {
        // update-begin-Autor: wjb date: 2022-02-09 10:47 for: 生成单据编号
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("prefix","JK"); // 编码前缀
        Object result = FillRuleUtil.executeRule("common_code", jsonObj);
        eaLoanbill.setBillNo(result.toString());
        // update-end-Autor: wjb date: 2022-02-09 10:47 for: 生成单据编号
        eaLoanbill.setState(0);
        if(StringUtils.isNotBlank(eaLoanbill.getIndexId())){
            String indexIdName = ncInoutbusiclassService.getIndexIdName(eaLoanbill.getIndexId());
            eaLoanbill.setIndexIdName(indexIdName);
        }
        eaLoanbillService.save(eaLoanbill);
        return Result.OK(eaLoanbill);
    }

    /**
     * 编辑
     *
     * @param eaLoanbill
     * @return
     */
    @AutoLog(value = "借款单-编辑")
    @ApiOperation(value = "借款单-编辑", notes = "借款单-编辑")
    @PostMapping(value = "/edit")
    public Result<?> edit(@RequestBody EaLoanbill eaLoanbill) {
        eaLoanbillService.updateById(eaLoanbill);
        return Result.OK(eaLoanbill);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "借款单-通过id删除")
    @ApiOperation(value = "借款单-通过id删除", notes = "借款单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        QueryWrapper<EaLoanbill> params = new QueryWrapper<>();
        params.eq("id",id);
        EaLoanbill eaLoanbill = eaLoanbillService.getOne(params);
        if(eaLoanbill != null && eaLoanbill.getState() > 0){
            return Result.error("该单据已发起流程,不可删除!");
        }
        eaLoanbillService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "借款单-批量删除")
    @ApiOperation(value = "借款单-批量删除", notes = "借款单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.eaLoanbillService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "借款单-通过id查询", notes = "借款单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        EaLoanbill eaLoanbill = eaLoanbillService.getById(id);
        if (eaLoanbill == null) {
            return Result.error("未找到对应数据");
        }
        // 返回借款人中文
        if(StringUtils.isNotBlank(eaLoanbill.getPersonId())){
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaLoanbill.getPersonId());
            if (ncPersonnel != null){
                eaLoanbill.setPersonIdName(ncPersonnel.getName());
            }
        }
        return Result.OK(eaLoanbill);
    }

    /**
    * @Description 借款单打印模板-通过id查询
    * @author  wujinbiao
    * @date 2022/2/8
    * @param id
    * @return
    */
    @ApiOperation(value = "借款单打印模板-通过id查询", notes = "借款单打印模板-通过id查询")
    @GetMapping(value = "/selectById")
    public Result<?> selectById(@RequestParam(name = "id", required = true) String id) {
        EaLoanBillPrintVo eaLoanBillPrintVo = new EaLoanBillPrintVo();
        EaLoanbill eaLoanbill = eaLoanbillService.getById(id);
        if (eaLoanbill == null) {
            return Result.error("未找到对应数据");
        }
        BeanUtils.copyProperties(eaLoanbill,eaLoanBillPrintVo);
        if (StringUtils.isNotBlank(eaLoanbill.getPersonId())){
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaLoanbill.getPersonId());
            if(ncPersonnel != null){
                eaLoanBillPrintVo.setPersonIdName(ncPersonnel.getName());   // 借款人中文
            }
        }
        if(StringUtils.isNotBlank(eaLoanbill.getIndexId())){
            String indexIdName = ncInoutbusiclassService.getIndexIdName(eaLoanbill.getIndexId());
            eaLoanBillPrintVo.setIndexIdName(indexIdName);
        }

        // 借款金额转为大写金额
        BigDecimal loanAmount = eaLoanbill.getLoanAmount() != null ? eaLoanbill.getLoanAmount() : new BigDecimal(0);
        String loanAmountStr = ConvertUpMoneyUtil.toChinese(String.valueOf(loanAmount));
        eaLoanBillPrintVo.setLoanAmount_cn(loanAmountStr);  // 借款金额

        //审批流程
        // update-begin-Autor: wjb date: 2022-02-10 14:50 for: 添加流程审批记录
        if (StringUtils.isNotBlank(eaLoanbill.getProcInstId())){
            List<Map<String, Object>> nodeList = activityCommonService.getNodeList(eaLoanbill.getProcInstId());
            eaLoanBillPrintVo.setSpjl(nodeList);
        }
        // update-end-Autor: wjb date: 2022-02-10 14:50 for: 添加流程审批记录

        return Result.OK(eaLoanBillPrintVo);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param eaLoanbill
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, EaLoanbill eaLoanbill) {
        return super.exportXls(request, eaLoanbill, EaLoanbill.class, "ea_loanbill");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, EaLoanbill.class);
    }

}
